﻿using UnityEngine;
using System.Collections;

public class Connect : MonoBehaviour
{
	public string connectToIP = "127.0.0.1";
	public int connectPort = 25001;
	public bool useNat = false;

	void OnGUI()
	{
		if (Network.peerType == NetworkPeerType.Disconnected)
		{
			GUILayout.Label("Connection status: Disconnected");

			connectToIP = GUILayout.TextField(connectToIP, GUILayout.MinWidth(100));
			connectPort = int.Parse(GUILayout.TextField(connectPort.ToString()));

			GUILayout.BeginVertical();
			if (GUILayout.Button("Connect as client"))
			{
				Network.Connect(connectToIP, connectPort);
			}

			if (GUILayout.Button("Start Server"))
			{
				Network.InitializeServer(32, connectPort, useNat);
			}

			GUILayout.EndVertical();
		}
		else
		{
			//We've got a connection(s)!
			if (Network.peerType == NetworkPeerType.Connecting)
			{
				GUILayout.Label("Connection status: Connecting");
			}
			else if (Network.peerType == NetworkPeerType.Client)
			{
				GUILayout.Label("Connection status: Client!");
				GUILayout.Label("Ping to server: " +
				                Network.GetAveragePing(Network.connections[0]));
			}
			else if (Network.peerType == NetworkPeerType.Server)
			{
				GUILayout.Label("Connection status: Server!");
				GUILayout.Label("Connections: " + Network.connections.Length);
				if (Network.connections.Length >= 1)
				{
					GUILayout.Label("Ping to first player: " +
					                Network.GetAveragePing(Network.connections[0]));
				}
			}

			if (GUILayout.Button("Disconnect"))
			{
				Network.Disconnect(200);
			}
		}
	}

	void OnConnectedToServer()
	{
		Debug.Log("This CLIENT has connected to a server");
	}

	void OnDisconnectedFromServer(NetworkDisconnection info)
	{
		Debug.Log("This SERVER OR CLIENT has disconnected from a server");
	}

	void OnFailedToConnect(NetworkConnectionError error)
	{
		Debug.Log("Could not connect to server: " + error);
	}

	void OnPlayerConnected(NetworkPlayer player)
	{
		Debug.Log("Player connected from: " + player.ipAddress + ":" + player.port);
	}

	void OnServerInitialized()
	{
		Debug.Log("Server initialized and ready");
	}

	void OnPlayerDisconnected(NetworkPlayer player)
	{
		Debug.Log("Player disconnected from: " + player.ipAddress + ":" + player.port);
	}

	void OnFailedToConnectToMasterServer(NetworkConnectionError info)
	{
		Debug.Log("Could not connect to master server: " + info);
	}

	void OnNetworkInstantiate(NetworkMessageInfo info)
	{
		Debug.Log("New object instantiated by " + info.sender);
	}

	void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
	{
	}
}